<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card class="box-card">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              style="margin-bottom: 20px"
              @click="showDialogFn"
            >新增角色</el-button>
            <el-table
              v-loading="loading"
              :data="tableData"
              border
            >
              <el-table-column
                label="序号"
                type="index"
                width="120"
                align="center"
                :index="indexMethod"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="240"
                align="center"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column
                label="操作"
                align="center"
                width="300"
              >
                <template v-slot="{row}">
                  <el-button size="small" type="success" icon="el-icon-set-up" @click="assignPermission(row)">分配权限</el-button>
                  <el-button size="small" type="primary" icon="el-icon-edit-outline" @click="edit(row)">编辑</el-button>
                  <el-button size="small" type="danger" icon="el-icon-delete" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- // 页码 -->
            <el-row type="flex" justify="end" style="margin-top: 10px">
              <el-pagination
                layout="prev, pager, next"
                :total="total"
                :page-size="pagesize"
                :current-page="page"
                background
                @current-change="changeFn"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              style="margin-bottom: 50px"
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px">
              <el-form-item label="企业名称">
                <el-input disabled style="width: 400px" :value="company.name" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v disabled style="width: 400px" :value="company.companyAddress" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input disabled style="width: 400px" :value="company.mailbox" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" :rows="3" disabled style="width: 400px" :value="company.remarks" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- // 添加 编辑角色的弹窗 -->
      <el-dialog :title="showTitle" :visible="showDialog" width="40%" top="20vh" @close="close">
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="角色名称" label-width="100px" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" label-width="100px">
            <el-input
              v-model="form.description"
              type="textarea"
              placeholder="请输入角色描述"
              rows="2"
              resize="none"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="add">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 角色分配权限弹窗 -->
      <el-dialog title="分配权限" :visible.sync="showPermissionDialog" width="30%">
        <el-tree
          ref="tree"
          v-loading="Permissionloading"
          :data="permissonList"
          default-expand-all
          show-checkbox
          node-key="id"
          :props="defaultProps"
          check-strictly
        />
        <template #footer>
          <el-button @click="showPermissionDialog=false">取消</el-button>
          <el-button type="primary" @click="addRolePermission">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { addRole, delRole, getRoleDetail, getRoleList, editRole, getCompanyInfo, assignPrem } from '@/api/settings'
import { mapState } from 'vuex'
import { getPermissionList } from '@/api/permission'
import { listToTree } from '@/api/departments'
export default {
  name: 'Setting',
  data() {
    return {
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { max: 8, message: '不能超过8个字符', trigger: 'blur' }
        ]
      },
      activeName: 'role',
      tableData: [], // 角色列表
      page: 1, // 页码
      pagesize: 10, // 每页条数
      total: 0, // 总共数据条数
      loading: false, // loading加载
      showDialog: false, // 控制弹窗显示隐藏
      company: {}, // 公司信息
      showPermissionDialog: false, // 分配权限的弹窗
      permissonList: [], // 所有权限点列表
      defaultProps: {
        label: 'name'
      },
      Permissionloading: false,
      rolePermissionList: [], // 当前角色权限列表
      roleId: '' // 当前角色id
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      this.loading = true
      const { rows, total } = await getRoleList(this.page, this.pagesize)
      // console.log(rows)
      this.tableData = rows
      this.total = total
      this.loading = false
    },
    // 当前页数currentpage改变时触发的函数
    changeFn(value) {
      this.page = value
      this.getRoleList()
    },
    indexMethod(index) {
      // 序号小标的显示:每页显示的条数 * 前面的页数 + 下标从1开始
      return this.pagesize * (this.page - 1) + index + 1
    },
    // 删除角色
    async del(id) {
      // console.log(id)
      try {
        await this.$confirm('您确定删除此角色吗?', '温馨提示', { type: 'warning' })
      } catch {
        return
      }
      // 发请求删除角色
      await delRole(id)
      // 删除成功提示
      this.$message.success('删除角色成功')
      // 如果当前页码 只剩一条数据的时候,删除成功后因该显示上一页的数据
      if (this.tableData.length === 1 && this.page > 1) {
        this.page--
      }
      // 发请求重新渲染角色列表
      this.getRoleList()
    },
    close() {
      this.showDialog = false
      // 关闭弹窗的时候重置表单信息和校验信息
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    showDialogFn() {
      this.showDialog = true
    },
    // 添加角色
    async add() {
      try {
        // 表单校验通过才会继续往下执行，失败会走catch
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.form.id) {
        await editRole(this.form)
        this.$message.success('修改成功')
      } else {
        // 发送请求添加角色
        await addRole(this.form)
        // 提示消息
        this.$message.success('添加角色成功')
        // 添加成功后跳转到最后一页
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
      }
      // 关闭弹窗
      this.showDialog = false
      // 重新渲染
      this.getRoleList()
    },
    // 编辑角色
    async edit(row) {
      // 信息的回显
      const data = await getRoleDetail(row.id)
      this.form = data
      this.showDialog = true
    },
    // 获取公司信息
    async getCompanyInfo() {
      // console.log(this.userInfo)
      // console.log(this.$store.state.user.userInfo)
      const data = await getCompanyInfo(this.userInfo.companyId)
      // console.log(data)
      this.company = data
    },
    // 点击分配权限
    async assignPermission(row) {
      this.roleId = row.id
      this.Permissionloading = true
      // console.log(row)
      this.showPermissionDialog = true
      const data = await getPermissionList()
      // console.log(data)
      this.permissonList = listToTree(data, '0')
      this.Permissionloading = false
      const res = await getRoleDetail(row.id)
      // console.log(res)
      // 储存当前角色权限点列表
      this.rolePermissionList = res.permIds
      // 设置角色已有的权限点
      this.$refs.tree.setCheckedKeys(this.rolePermissionList)
    },
    // 确定给角色添加权限点
    async addRolePermission() {
      // 获取当前角色的权限点
      const result = this.$refs.tree.getCheckedKeys()
      // 发送请求添加权限点
      await assignPrem(this.roleId, result)
      this.$message.success('添加权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
